package auth;



import bese.Header;
import bese.NettyMessage;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * 登录认证
 * Created by wuhui on 2016/8/4.
 */
@Slf4j
public class LoginAuthReqHandler extends ChannelHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(buildLoginReq());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage nettyMessage = (NettyMessage) msg;
        //如果是握手应答消息,需要判断是否认证成功
        if(nettyMessage.getHeader()!=null&&nettyMessage.getHeader().getType()==1){
            byte loginResule = (byte) nettyMessage.getBody();
            if(loginResule!=0){
                //握手失败，关闭连接
                ctx.close();
            }else{
                ctx.fireChannelRead(msg);
            }
        }else{
            ctx.fireChannelRead(msg);
        }

    }


    /**
     * 构造登录消息
     * @return
     */
    private NettyMessage buildLoginReq(){
        NettyMessage message = new NettyMessage();
        Header header = new Header();
        header.setType((byte)1);
        message.setHeader(header);
        return  message;
    }

}
